<template>
  <div class="app-container">
    <!-- 查询表单区域，保持与其他页面一致的行内布局 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <!-- 作者ID -->
      <el-form-item label="作者ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入作者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 菜谱标题 -->
      <el-form-item label="菜谱标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入菜谱标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 浏览量 -->
      <el-form-item label="浏览量" prop="viewCount">
        <el-input
          v-model="queryParams.viewCount"
          placeholder="请输入浏览量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏，布局与其他页面统一 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['collect:recipes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['collect:recipes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:recipes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['collect:recipes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格，添加边框、斑马纹，优化样式一致性 -->
    <el-table v-loading="loading" :data="recipesList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="菜谱唯一ID" align="center" prop="id" />
      <el-table-column label="作者ID" align="center" prop="userId" />
      <el-table-column label="菜谱标题" align="center" prop="title" />
      <el-table-column label="媒体类型：1-图片，2-视频" align="center" prop="mediaType">
        <template slot-scope="scope">
          {{ scope.row.mediaType === 1 ? '图片' : '视频' }}
        </template>
      </el-table-column>
      <el-table-column label="封面资源URL" align="center" prop="coverUrl" />
      <el-table-column label="通用简介" align="center" prop="introduction" />
      <el-table-column label="视频补充描述" align="center" prop="videoDescription" />
      <el-table-column label="视频时长" align="center" prop="videoDuration" />
      <el-table-column label="浏览量" align="center" prop="viewCount" />
      <el-table-column label="关联耗时表" align="center" prop="cookTimeId" />
      <el-table-column label="关联难度表" align="center" prop="difficultyId" />
      <el-table-column label="关联分类表" align="center" prop="categoryId" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="collectCount" />
      <el-table-column label="是否删除" align="center" prop="del">
        <template slot-scope="scope">
          {{ scope.row.del === 0 ? '正常' : '已删除' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collect:recipes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:recipes:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件，与其他页面保持一致 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗，优化表单布局和交互 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 作者ID -->
        <el-form-item label="作者ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入作者ID" />
        </el-form-item>
        <el-form-item label="菜谱标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入菜谱标题" />
        </el-form-item>
        <el-form-item label="封面资源URL" prop="coverUrl">
          <el-input v-model="form.coverUrl" placeholder="请输入封面资源URL" />
        </el-form-item>
        <el-form-item label="通用简介" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入通用简介" />
        </el-form-item>
        <el-form-item label="视频补充描述" prop="videoDescription">
          <el-input v-model="form.videoDescription" placeholder="请输入视频补充描述" />
        </el-form-item>
        <el-form-item label="是否删除" prop="del">
          <el-radio-group v-model="form.del">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 可根据实际需求补充其他必要表单字段，如浏览量等 -->
        <el-form-item label="浏览量" prop="viewCount">
          <el-input v-model="form.viewCount" placeholder="请输入浏览量" />
        </el-form-item>
        <!-- 其他原有字段可按需保留/调整 -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listRecipes, getRecipes, delRecipes, addRecipes, updateRecipes } from "@/api/collect/recipes";
import Pagination from "@/components/Pagination";
import RightToolbar from "@/components/RightToolbar";

export default {
  name: "Recipes",
  components: { Pagination, RightToolbar },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      recipesList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null, // 作者ID查询条件
        title: null, // 菜谱标题查询条件
        viewCount: null, // 浏览量查询条件
        mediaType: null,
        coverUrl: null,
        introduction: null,
        videoDescription: null,
        videoDuration: null,
        cookTimeId: null,
        difficultyId: null,
        categoryId: null,
        status: null,
        collectCount: null,
        del: null,
      },
      form: {
        id: null,
        userId: null, // 作者ID
        title: null,
        mediaType: null,
        coverUrl: null,
        introduction: null,
        videoDescription: null,
        videoDuration: null,
        viewCount: null, // 浏览量
        cookTimeId: null,
        difficultyId: null,
        categoryId: null,
        createTime: null,
        status: null,
        collectCount: null,
        del: 0, // 默认正常
      },
      rules: {
        userId: [
          { required: true, message: "作者ID不能为空", trigger: "blur" },
        ],
        title: [
          { required: true, message: "菜谱标题不能为空", trigger: "blur" },
        ],
        coverUrl: [
          { required: true, message: "封面资源URL不能为空", trigger: "blur" },
        ],
        introduction: [
          { required: false, message: "通用简介", trigger: "blur" }, 
        ],
        videoDescription: [
          { required: false, message: "视频补充描述", trigger: "blur" }, 
        ],
        del: [
          { required: true, message: "是否删除不能为空", trigger: "change" },
        ],
        viewCount: [
          { required: true, message: "浏览量不能为空", trigger: "blur" },
        ],
        // 其他原有校验规则按需保留
        mediaType: [
          { required: true, message: "媒体类型不能为空", trigger: "change" },
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
        collectCount: [
          { required: true, message: "收藏数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询菜谱管理列表 */
    getList() {
      this.loading = true;
      listRecipes(this.queryParams)
        .then((response) => {
          this.recipesList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取列表失败:", error);
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.resetForm();
    },
    // 表单重置
    resetForm() {
      this.form = {
        id: null,
        userId: null,
        title: null,
        mediaType: null,
        coverUrl: null,
        introduction: null,
        videoDescription: null,
        videoDuration: null,
        viewCount: null,
        cookTimeId: null,
        difficultyId: null,
        categoryId: null,
        createTime: null,
        status: null,
        collectCount: null,
        del: 0,
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加菜谱管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      const id = row ? row.id : this.ids[0];
      getRecipes(id)
        .then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改菜谱管理";
        })
        .catch((error) => {
          console.error("获取详情失败:", error);
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const request = this.form.id ? updateRecipes : addRecipes;
          request(this.form)
            .then(() => {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            })
            .catch((error) => {
              this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      this.$modal.confirm(`是否确认删除菜谱管理编号为"${ids}"的数据?`).then(() => {
        delRecipes(ids)
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch((error) => {
            this.$modal.msgError("删除失败：" + (error.message || "未知错误"));
          });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "collect/recipes/export",
        { ...this.queryParams },
        `recipes_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
/* 统一表格和弹窗样式，与其他页面保持视觉一致性 */
::v-deep .el-table {
  width: 100%;
}
.dialog-footer {
  text-align: right;
}
.small-padding ::v-deep .cell {
  padding: 5px 0 !important;
}
</style>